﻿/// <reference path="jquery-1.8.2-vsdoc.js" />

$(function () {
    setupFunctions();
});

function setupFunctions() {
    /***********************************************************/
    $(".tabs-left-list li").click(function () {
        var increment = $(this).attr("data-id");
        var value = 87 - (increment * 3);
        var cssObj1 = {
            'background-color': "#E8E8EB !important",
            'border-right': "none"
        }
        $(".tabs-left-list li").css(cssObj1);
        var cssObj2 = {
            'background-color': "rgb(" + value + "," + value + "," + value + ") !important",
            'border-right': "1px solid " + "rgb(" + value + "," + value + "," + value + ")"
        }
        $(".tabs-left-list li.ui-tabs-active").css(cssObj2);
    })
    /***********************************************************/
    if ($.browser.mozilla) $('body').addClass('mozilla');
    if ($.browser.msie && $.browser.version > 8) $('html').addClass('ie-newer');
    if ($.browser.msie && $.browser.version == 8) $('html').addClass('ie8');
    if ($.browser.msie && $.browser.version == 7) $('html').addClass('ie7');
    /***********************************************************/
    if ($(window).width() <= 960) {
        $('body').addClass('mobile');
    }
    else if ($(window).width() > 960) {
        $('body').removeClass('mobile');        
    }

    if ($(window).width() < 640) {
        $('input').removeClass('tooltip');
        $('a').removeClass('tooltip');
        //Remove all class for dialog
        $('span.dialog-remove-invitation a').removeClass('remove-invitation');
        $('span.dialog-leave-group a').removeClass('leave-group');
    }
    /***********************************************************/
    $(".tooltip").tooltip();

    $('input, textarea').placeholder();

    $("#accordion").accordion({
        collapsible: true,
        hightStyle: "content",
        icons: { "header": "ui-icon-plus", "headerSelected": "ui-icon-minus" }
    });

    $("a.subpage-back").click(function (event) {
        //event.preventDefault();
    });

    $(".tabs-dashboard").tabs();

    $.datepicker.setDefaults({
        dateFormat: 'dd/mm/yy'
    });

    $(".datepicker").datepicker();

    $(".datepicker-mobile").datepicker();

    $(".tabs-bids").tabs();

    $(".invitations").click(function () {
        $(".invitations-list").slideToggle("fast");
    });
    $(".invitations").mouseleave(function () {
        $(".invitations-list").stop().slideUp();
    });

    $(".notifications").click(function () {
        $(".notifications-list").slideToggle("fast");
    });
    $(".notifications").mouseleave(function () {
        $(".notifications-list").stop().slideUp();
    });

    /***********************************************************/
    /* Create group form*/
    var $formCreateGroup = $(".cb-create-group-form-container");
    $("#create-group-inline").colorbox({ inline: true, href: $formCreateGroup, width: "350", height: "500",
        onOpen: function () { $(".cb-create-group-form-container").show() },
        onClosed: function () { $(".cb-create-group-form-container").hide() }
    });

    create_group_initialization();
    create_group_add_member();
    create_group_remove_member();
    create_group_submit();

    /*Create group autocomplete input field*/
    $("input.create-group-input").autocomplete({
        source: function (request, response) {
            $.ajax({
                type: "GET",
                contentType: "application/json; charset=utf-8",
                url: "/Action/CollectUsernames/",
                data: { query: request.term },
                dataType: "json",

                success: function (data) {
                    response($.map(data, function (item) {
                        return { label: item.name + " (" + item.username + ")", value: item.username };
                    }))
                }
            });
        },
        minLength: 3
    });
    /***********************************************************/
    /* Make bid form */
    var $formMakeBid = $(".cb-make-bid-form-container");
    $("#make-bid-inline").colorbox({ inline: true, href: $formMakeBid, width: "350", height: "655",
        onOpen: function () { $(".cb-make-bid-form-container").show() },
        onClosed: function () { $(".cb-make-bid-form-container").hide() }
    });

    $(".group-selection").live("click", function () {
        $(".make-bid-form-errors").empty();
        $(".group-selection-list").removeClass("input-validation-error");
        $(".group-selection-list").removeAttr('disabled');
        //Disable spinner
        $(".spinner-make-bid").spinner("disable");
        $(".available-balance").text("");
        $('.group-selection-list').prop('selectedIndex', 0);
    });
    $(".single-selection").live("click", function () {
        $(".make-bid-form-errors").empty();
        $(".group-selection-list").removeClass("input-validation-error");
        $(".group-selection-list").attr('disabled', 'disabled');
        var currentUserBalance = $(".available-credit input").val();
        $(".available-balance").text(currentUserBalance);
        //Enable spinner
        $(".spinner-make-bid").spinner("option", "max", currentUserBalance);
        $(".spinner-make-bid").spinner("enable");
        $('.group-selection-list').prop('selectedIndex', 0);
    });

    $(".group-selection-list").live("change", function () {
        $(".make-bid-form-errors").empty();
        $(".group-selection-list").removeClass("input-validation-error");
        //update slider balance;
        var id = $(this).attr("value");
        if (id === "") {
            $(".available-balance").text("");
            //Disable
            $(".spinner-make-bid").spinner("disable");
        }
        else {
            var balance = $(".group-balance-" + id).attr("data-val");
            //Enable
            $(".spinner-make-bid").spinner("option", "max", balance);
            $(".available-balance").text(balance);
            $(".spinner-make-bid").spinner("enable");
        }
    });

    // validation fix for group selection
    var is = $(".group-selection").attr("checked");
    if (is != undefined && is === "checked") {
        $(".available-balance").text("");
        $("#biddingAmount").attr('disabled', 'disabled');
        $(".group-selection-list").removeAttr('disabled');
        $(".bid-slider").slider("option", "disabled", true); 
    }
    /******************************************************/

    /* Invite functionality for autocomplete */
    $(".invite-group-input").keypress(function () {
        $(".invite-group-form-errors").empty();
        $(".invite-group-input").removeClass("input-validation-error");
    });
    $(".invite-group-form").submit(function () {
        //Remove all member validations
        $(".invite-group-form-errors").empty();

        var inputName = $(".invite-group-input").val();
        var valid = true;
        if (inputName == "") {
            //add validation message to view
            var error = document.createElement("p");
            $(error).attr("class", "invite-groups-form-errors-input");
            $(error).text("No group member has been chosen.");

            $(".invite-group-form-errors").append(error);

            $(".invite-group-input").addClass("input-validation-error");
            $(".invite-group-input").attr("value", "");
            return false;
        }
        $.ajax({
            type: 'POST',
            async: false,
            url: "/Groups/CheckUsername",
            data: { query: inputName, id: $(".groupid-invite-form").val() },
            success: function (data) {
                //if valid username: then add
                if (data !== "") {
                    valid = true;
                }
                else {
                    //add validation message to view: member does not exist
                    var error = document.createElement("p");
                    $(error).attr("class", "invite-groups-form-errors-input");
                    $(error).text("Member to add field is invalid.")
                    $(".invite-group-form-errors").append(error);
                    $(".invite-group-input").addClass("input-validation-error");
                    $(".invite-group-input").attr("value", "");
                    valid = false;
                }
            }
        });
        return valid;
    });

    $("input.invite-group-input").autocomplete({        
        source: function (request, response) {
            $.ajax({
                type: "GET",
                contentType: "application/json; charset=utf-8",
                url: "/Groups/CollectUsernames/",
                data: { query: request.term , id: $(".groupid-invite-form").val()},
                dataType: "json",

                success: function (data) {
                    response($.map(data, function (item) {
                        return { label: item.name + " (" + item.username + ")", value: item.username };
                    }))
                }
            });
        },
        minLength: 3
    });
    /*****************************************/

}

/*********************************************************************/
function create_group_initialization() {    
    var first = true;
    $("input.create-group-input").each(function () {
        
        if ($(this).val() !== "") {
            
            var elemCont = document.createElement("div");
            $(elemCont).attr("class", $(this).attr('id'));

            var elem = document.createElement("input");
            $(elem).attr("value", $(this).val());
            $(elem).attr("disabled", "disabled");
            $(elem).attr("type", "text");

            var elemRemove = document.createElement("span");
            $(elemRemove).attr("class", "remove-member-input");

            $(elemCont).append(elem);
            $(elemCont).append(elemRemove);

            $(".added-inputs").append(elemCont);
            $(this).addClass("hide");
            $(this).addClass("added-member");
            $(this).parent().addClass("added-member");
            $("div." + $(this).attr('id')).removeClass("available");
        }
        else if ($(this).val() === "") {
            if (first) {
                //do not show
                first = false;
                var id = $(this).attr('id');
                $("div." + id).removeClass("hide");
            }
            else {
                //keep hidden
            }
        }
    });
}
/*********************************************************************/
function create_group_add_member() {
    $(".add-member-input").click(function () {
        //Remove all member validations
        $(".create-group-form-errors-script").empty();

        var id = $(this).attr("data-id");
        var inputName = $("input#" + id).val();
        //if member was already added
        var duplicate = false;
        $("input.create-group-input").each(function () {            
            if ($(this).val() === inputName && id !== $(this).attr("id")) {
                duplicate = true;
                return;
            }
        });
        if (duplicate === true && inputName !== "") {
            //add validation message to view: member already added
            var error = document.createElement("span");
            $(error).attr("class", "create-groups-form-errors-input");
            $(error).text("Member has already been added.");
            $(".create-group-form-errors-script").append(error);

            $("input#" + id).addClass("input-validation-error-script");
            $("input#" + id).attr("value", "");
            return false;
        }
        $.post("/Action/CheckUsername", { query: inputName },
            function (data) {
                //if valid username: then add
                if (data !== "") {                    
                    var elemCont = document.createElement("div");
                    $(elemCont).attr("class", id);

                    var elem = document.createElement("input");
                    $(elem).attr("value", $("input#" + id).val());
                    $(elem).attr("disabled", "disabled");
                    $(elem).attr("type", "text");

                    var elemRemove = document.createElement("span");
                    $(elemRemove).attr("class", "remove-member-input");

                    $(elemCont).append(elem);
                    $(elemCont).append(elemRemove);

                    $(".added-inputs").append(elemCont);

                    $("div.create-group-input." + id).addClass("hide");
                    $("div.create-group-input." + id).addClass("added-member");
                    $("div.create-group-input." + id).removeClass("available");
                    $("input#" + id).attr("value", $("input#" + id).val());
                    $("input#" + id).addClass("added-member");
                    var div = $("div.available.create-group-input:first");
                    div.removeClass("hide");
                }
                else {
                    //Add error member doesnt exists
                    //add validation message to view: member does not exist
                    var error = document.createElement("span");
                    $(error).attr("class", "create-groups-form-errors-input");
                    $(error).text("Member does not exist.")
                    $(".create-group-form-errors-script").append(error);

                    $("input#" + id).addClass("input-validation-error");
                    $("input#" + id).attr("value", "");
                }
            });
    });
}
/*********************************************************************/
function create_group_remove_member() {
    $(".remove-member-input").live("click", function () {
        var id = $(this).parent().attr("class");
        $("input#" + id).removeClass("added-member");
        $("input#" + id).removeClass("hide");
        $("input#" + id).attr("value", "");
        $(".available-inputs div." + id).addClass("available");        
        $(this).parent().remove();
        $("div.available.create-group-input").addClass("hide");
        var div = $("div.available.create-group-input:first");
        div.removeClass("hide");
    });
}
/*********************************************************************/
function create_group_submit() {
    $(".create-group-input").keypress(function () {
        $(".create-group-form-errors-script").empty();
    });

    $(".create-group-form").submit(function () {        
        //Remove all member validations
        $(".create-group-form-errors-script").empty();

        var input = $("div.available.create-group-input:first input");
        var id = input.attr("id");
        var inputName = input.val();

        //check if not input members have been added
        var empty = true;
        $("input.create-group-input").each(function () {
            if ($(this).val() !== "") {
                empty = false;
            }
        });
        if (empty) {
            //add validation message to view ("no group members have been added!")
            var error = document.createElement("span");
            $(error).attr("class", "create-groups-form-errors-input");
            $(error).text("No group members have been added.");

            $(".create-group-form-errors-script").append(error);

            $("input#" + id).addClass("input-validation-error");
            $("input#" + id).attr("value", "");
            return false;
        }
        var valid = true;

        if (inputName !== "") {
            //if member was already added
            var duplicate = false;
            $("input.create-group-input").each(function () {
                if ($(this).val() === inputName && id !== $(this).attr("id")) {
                    duplicate = true;
                    return;
                }
            });
            if (duplicate === true) {
                //add validation message to view: member already added
                var error2 = document.createElement("span");
                $(error2).attr("class", "create-groups-form-errors-input");
                $(error2).text("Member has already been added.");

                $(".create-group-form-errors-script").append(error2);
                $("input#" + id).addClass("input-validation-error");
                $("input#" + id).attr("value", "");
                return false;
            }
            $.ajax({
                type: 'POST',
                async: false,
                url: "/Action/CheckUsername",
                data: { query: inputName },
                success: function (data) {
                    //if valid username: then add
                    if (data !== "") {
                        var elemCont = document.createElement("div");
                        $(elemCont).attr("class", id);

                        var elem = document.createElement("input");
                        $(elem).attr("value", inputName);
                        $(elem).attr("disabled", "disabled");
                        $(elem).attr("type", "text");

                        var elemRemove = document.createElement("span");
                        $(elemRemove).attr("class", "remove-member-input");

                        $(elemCont).append(elem);
                        $(elemCont).append(elemRemove);

                        $(".added-inputs").append(elemCont);

                        //$("div." + id).addClass("hide");
                        $("div.create-group-input." + id).addClass("hide");
                        $("div." + id).addClass("added-member");
                        $("div." + id).removeClass("available");
                        $("input#" + id).attr("value", inputName);
                        $("input#" + id).addClass("added-member");
                        var div = $("div.available.create-group-input:first");
                        div.removeClass("hide");
                    }
                    else {
                        //add validation message to view: member does not exist
                        var error = document.createElement("span");
                        $(error).attr("class", "create-groups-form-errors-input");
                        $(error).text("Member does not exist.")
                        $(".create-group-form-errors-script").append(error);

                        $("input#" + id).addClass("input-validation-error");
                        $("input#" + id).attr("value", "");
                        valid = false;
                    }
                }
            });
        }
        return valid
    });
}
/*********************************************************************/
function validateMakeBid() {    
    var id = $(".group-selection-list").attr("value");
    if ($(".group-selection-list").attr('disabled') !== "disabled" && id === "") {
        $(".group-selection-list").addClass("input-validation-error");
        var elem = document.createElement("span");
        $(elem).attr("class", "field-validation-error");
        $(elem).text("Group selection is required")
        $(".make-bid-form-errors").append(elem);
        return false;
    }
    return true;
}
/*********************************************************************/
function goBack() {
    window.history.back()
}
/*********************************************************************/
/*! http://mths.be/placeholder v2.0.7 by @mathias */
; (function (f, h, $) { var a = 'placeholder' in h.createElement('input'), d = 'placeholder' in h.createElement('textarea'), i = $.fn, c = $.valHooks, k, j; if (a && d) { j = i.placeholder = function () { return this }; j.input = j.textarea = true } else { j = i.placeholder = function () { var l = this; l.filter((a ? 'textarea' : ':input') + '[placeholder]').not('.placeholder').bind({ 'focus.placeholder': b, 'blur.placeholder': e }).data('placeholder-enabled', true).trigger('blur.placeholder'); return l }; j.input = a; j.textarea = d; k = { get: function (m) { var l = $(m); return l.data('placeholder-enabled') && l.hasClass('placeholder') ? '' : m.value }, set: function (m, n) { var l = $(m); if (!l.data('placeholder-enabled')) { return m.value = n } if (n == '') { m.value = n; if (m != h.activeElement) { e.call(m) } } else { if (l.hasClass('placeholder')) { b.call(m, true, n) || (m.value = n) } else { m.value = n } } return l } }; a || (c.input = k); d || (c.textarea = k); $(function () { $(h).delegate('form', 'submit.placeholder', function () { var l = $('.placeholder', this).each(b); setTimeout(function () { l.each(e) }, 10) }) }); $(f).bind('beforeunload.placeholder', function () { $('.placeholder').each(function () { this.value = '' }) }) } function g(m) { var l = {}, n = /^jQuery\d+$/; $.each(m.attributes, function (p, o) { if (o.specified && !n.test(o.name)) { l[o.name] = o.value } }); return l } function b(m, n) { var l = this, o = $(l); if (l.value == o.attr('placeholder') && o.hasClass('placeholder')) { if (o.data('placeholder-password')) { o = o.hide().next().show().attr('id', o.removeAttr('id').data('placeholder-id')); if (m === true) { return o[0].value = n } o.focus() } else { l.value = ''; o.removeClass('placeholder'); l == h.activeElement && l.select() } } } function e() { var q, l = this, p = $(l), m = p, o = this.id; if (l.value == '') { if (l.type == 'password') { if (!p.data('placeholder-textinput')) { try { q = p.clone().attr({ type: 'text' }) } catch (n) { q = $('<input>').attr($.extend(g(this), { type: 'text' })) } q.removeAttr('name').data({ 'placeholder-password': true, 'placeholder-id': o }).bind('focus.placeholder', b); p.data({ 'placeholder-textinput': q, 'placeholder-id': o }).before(q) } p = p.removeAttr('id').hide().prev().attr('id', o).show() } p.addClass('placeholder'); p[0].value = p.attr('placeholder') } else { p.removeClass('placeholder') } } } (this, document, jQuery));
